package com.example.ass4;

import java.util.ArrayList;
import java.util.jar.Attributes.Name;


import adapter.MyArrayAdapter;
import android.support.v7.app.ActionBarActivity;
import android.app.Dialog;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.MailTo;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.RawContacts;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import data_model.*;

public class DanhbaActivity extends ActionBarActivity {
	ActionMode.Callback callback;
	ActionMode actionMode = null;
	ArrayList<Contact> arrList =null;
	MyArrayAdapter adapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_danhba);
		//==========================================================
		TextView tvfont = (TextView) findViewById(R.id.txtdanhba);
		Typeface typeface = Typeface.createFromAsset(getAssets(),
				"fonts/HoboStd.otf");
		tvfont.setTypeface(typeface);
		
		ListView list = (ListView) findViewById(R.id.listItems);
		arrList = new ArrayList<Contact>();
		adapter = new MyArrayAdapter(this, R.layout.layout_listview,arrList);
		
		Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);
		Cursor cursorMail = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, null,null, null);
		while (cursor.moveToNext()) {
			cursorMail.moveToNext();
			String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
			String email = cursorMail.getString(cursorMail.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
			Contact contact = new Contact(name, phoneNumber, email);
			arrList.add(contact);
		}
		cursor.close();
		cursorMail.close();
		list.setAdapter(adapter);
		//========================================Xu Ly=======================================
		callback=new ActionMode.Callback() {
			
			@Override
			public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public void onDestroyActionMode(ActionMode mode) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public boolean onCreateActionMode(ActionMode mode, Menu menu) {
				// TODO Auto-generated method stub
				getMenuInflater().inflate(R.menu.my_context_menu, menu);
				return true;
			}
			
			@Override
			public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
				// TODO Auto-generated method stub
				switch (item.getItemId()) {
				case R.id.remove:
					remove();
					break;
				case R.id.update:
					update();
					break;
				case R.id.add:
					add();
					break;
				}
				
				return true;
			
			}
		};
	}
	
	//========================Menu=======================
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.my_actionbar_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.call:
			Intent intent=new Intent(DanhbaActivity.this,ReadContactActivity.class);
			startActivity(intent);
			return true;
		case R.id.danhba:
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}
	//=================================Delete==================================
	public  boolean Delete(DanhbaActivity ctx, String phone, String name) {
	    Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
	    Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
	    try {
	        if (cur.moveToFirst()) {
	            do {
	                if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
	                    String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
	                    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
	                    ctx.getContentResolver().delete(uri, null, null);
	                    return true;
	                }

	            } while (cur.moveToNext());
	        }

	    } catch (Exception e) {
	        System.out.println(e.getStackTrace());
	    }
	    return false;
	}
	public void remove() {
		ArrayList<Contact> arrCopy = (ArrayList<Contact>) arrList.clone();
		for (Contact aGoods : arrCopy) {
			if (aGoods.isCheck()) {
				if(Delete(DanhbaActivity.this, aGoods.getNumber(), aGoods.getName()))
				arrList.remove(aGoods);
			}
		}
		adapter.notifyDataSetChanged();
		stopMenu();
	}
	//==================================Update==================================
	public void update_add(String ten,String sdt,String email) {
		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
		int rawContactInsertIndex = ops.size();
		ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
				.withValue(RawContacts.ACCOUNT_TYPE, null)
				.withValue(RawContacts.ACCOUNT_NAME, null).build());
		ops.add(ContentProviderOperation
				.newInsert(Data.CONTENT_URI)
				.withValueBackReference(Data.RAW_CONTACT_ID,
						rawContactInsertIndex)
				.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
				.withValue(StructuredName.DISPLAY_NAME,
						ten) 
				.build());
		ops.add(ContentProviderOperation
				.newInsert(Data.CONTENT_URI)
				.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
						rawContactInsertIndex)
				.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
				.withValue(Phone.NUMBER, sdt) 
				.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); 
		ops.add(ContentProviderOperation
				.newInsert(ContactsContract.Data.CONTENT_URI)
				.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
						rawContactInsertIndex)
				.withValue(
						Data.MIMETYPE,
						ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
				.withValue(ContactsContract.CommonDataKinds.Email.DATA,
						email)
				.withValue(
						Data.MIMETYPE,
						ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
				.withValue(ContactsContract.CommonDataKinds.Email.TYPE, "2")
				.build());

		try {
			ContentProviderResult[] res = getContentResolver().applyBatch(
					ContactsContract.AUTHORITY, ops);

		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (OperationApplicationException e) {
			e.printStackTrace();
		}
	
	}
	public void update() {
		final Dialog dialog = new Dialog(DanhbaActivity.this);
		dialog.setContentView(R.layout.layout_dialog);
		dialog.setTitle("Nhập Dữ Liệu Update");
		Button btnOK = (Button) dialog.findViewById(R.id.btnOK_dialog);
		Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel_dialog);
		final EditText edt1 = (EditText) dialog.findViewById(R.id.edt_dialog1);
		final EditText edt2 = (EditText) dialog.findViewById(R.id.edt_dialog2);
		final EditText edt3 = (EditText) dialog.findViewById(R.id.edt_dialog3);
		
		ArrayList<Contact> arrCopy = (ArrayList<Contact>) arrList.clone();
		for (Contact aGoods : arrCopy) {
			if (aGoods.isCheck()) {
				edt1.setText(aGoods.getName());
				edt2.setText(aGoods.getNumber());
				edt3.setText(aGoods.getEmail());
			}
		}
		btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		btnOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ArrayList<Contact> arrCopy = (ArrayList<Contact>) arrList.clone();
				for (Contact aGoods : arrCopy) {
					if (aGoods.isCheck()) {
						Delete(DanhbaActivity.this, aGoods.getNumber(),
								aGoods.getName());
						aGoods.setName(edt1.getText().toString());
						aGoods.setNumber(edt2.getText().toString());
						aGoods.setEmail(edt3.getText().toString());
						update_add(aGoods.getName(),aGoods.getNumber(),aGoods.getEmail());
						aGoods.setCheck(false);
					}
				}
				dialog.dismiss();
				adapter.notifyDataSetChanged();
				stopMenu();
			}
		});

		dialog.show();

	}
	//==============================Add===========================
	public void add()
	{
		final Dialog dialog = new Dialog(DanhbaActivity.this);
		dialog.setContentView(R.layout.layout_dialog);
		dialog.setTitle("Nhập Danh Bạ");
		Button btnAdd = (Button) dialog.findViewById(R.id.btnOK_dialog);
		Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel_dialog);
		final EditText edt1 = (EditText) dialog.findViewById(R.id.edt_dialog1);
		final EditText edt2 = (EditText) dialog.findViewById(R.id.edt_dialog2);
		final EditText edt3 = (EditText) dialog.findViewById(R.id.edt_dialog3);
		btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		btnAdd.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
	            int rawContactInsertIndex = ops.size();

	            ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
	                    .withValue(RawContacts.ACCOUNT_TYPE, null)
	                    .withValue(RawContacts.ACCOUNT_NAME, null).build());
	            ops.add(ContentProviderOperation
	                    .newInsert(Data.CONTENT_URI)
	                    .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
	                    .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
	                    .withValue(StructuredName.DISPLAY_NAME, edt1.getText().toString()) 
	                    .build());
	            ops.add(ContentProviderOperation
	                    .newInsert(Data.CONTENT_URI)
	                    .withValueBackReference(
	                            ContactsContract.Data.RAW_CONTACT_ID,   rawContactInsertIndex)
	                    .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
	                    .withValue(Phone.NUMBER,edt2.getText().toString()) 
	                    .withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); 
	            ops.add(ContentProviderOperation
	            	    .newInsert(ContactsContract.Data.CONTENT_URI)
	            	    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
	            	      rawContactInsertIndex)
	            	    .withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
	            	    .withValue(ContactsContract.CommonDataKinds.Email.DATA, edt3.getText().toString())
	            	    .withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
	            	    .withValue(ContactsContract.CommonDataKinds.Email.TYPE, "2").build());
	            
	            try
	            {
	            	ContentProviderResult[] res = getContentResolver().applyBatch(
	            		     ContactsContract.AUTHORITY, ops);
	            	
	            }
	            catch (RemoteException e)
	            { 
	            	e.printStackTrace();
	                // error
	            }
	            catch (OperationApplicationException e) 
	            {
	            	e.printStackTrace();
	                // error
	            }   		
				dialog.dismiss();
				arrList.add(new Contact(edt1.getText().toString(),edt2.getText().toString(),edt3.getText().toString()));
				adapter.notifyDataSetChanged();
			}
		});
		dialog.show();
	}
	public void startMenu() {
		if (actionMode == null) {
			actionMode = startActionMode(callback);
		}
	}

	public void stopMenu() {
		if (actionMode != null) {
			actionMode.finish();
			actionMode = null;
		}
	}
}
